import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gobelieve/common/style/style.dart';
import 'package:gobelieve/common/utils/global.dart';
import 'package:gobelieve/model/contacts.dart';
import 'package:gobelieve/provider/currentIndex.dart';
import 'package:gobelieve/provider/im_service.dart';
import 'package:provider/provider.dart';
import 'package:gobelieve/route/router.dart' as route;
import 'package:shared_preferences/shared_preferences.dart';

final route.Router router = route.Router();
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: ImService()),
        ChangeNotifierProvider.value(value: CurrentIndex()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyApp createState() => new _MyApp();
}

class _MyApp extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    SharedPreferences prefs;
    String _initialRoute = '/';
    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      String user = prefs.getString('user');
      // if (user != null && user.isNotEmpty) {
      //   /// 初始化user
      //   print("使用缓存内user");
      //   G.user.init(json.decode(user));
      // } else {
      /// 登陆逻辑, 这里暂时先模拟个假的登陆逻辑(也就是模拟中间件的用法)，没做页面
      /// _initialRoute = '/login';
      String token;
      var res = await G.req.user.authToken(22222);
      print("auth_token res : $res");
      token = res.data["data"];
      Map<String, dynamic> userTmp = {
        "uid": 22222,
        "appId": G.APP_ID,
        "token": token
      };
      G.user.init(userTmp);
      // }

      /// 异步查询好友列表，这里后期改成查询本地sqlite数据库+API同步好友列表
      var resF = await G.req.friend.friendList();
      List<dynamic> fList = resF.data["data"];
      print("好友列表长度： ${fList.length}");

      for (var item in fList) {
        Contact tmp = Contact.fromJson(item);
        Contact.contacts.add(tmp);
        Contact.mapContact[tmp.uid] = tmp; // 内存维护一个联系人列表
      }
    });

    return MaterialApp(
      navigatorKey: G.navigatorKey,
      title: '微信',
      theme: ThemeData.light().copyWith(
        primaryColor: Color(AppColors.PrimaryColor),
        cardColor: Color(AppColors.CardBgColor),
        backgroundColor: Color(AppColors.BackgroundColor),
      ),
      initialRoute: _initialRoute,
      onGenerateRoute: router.getRoutes,
    );
  }
}
